﻿#region Using Statements
using System;
using DirectZZT.Shared.Core;
using DirectZZT.Shared.World;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
#endregion

namespace DirectZZT.Gameplay
{
    /// <summary>
    /// Manages the worlds physically.
    /// </summary>
    public class WorldManager
    {
        #region Fields

        private List<WorldFile> _worldFiles;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the WorldManager class.
        /// </summary>
        public WorldManager()
        {
            _worldFiles = new List<WorldFile>();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Scans all available usable files.
        /// </summary>
        /// <param name="directory">The directory to scan. Leave blank for application directory.</param>
        public void Scan(string directory)
        {
            // get all serializers first
            var serializers = TypeManager.Instance.GetExports(typeof(IWorldSerializer)).Select(s => (IWorldSerializer)Activator.CreateInstance(s.Type)).ToList();

            DirectoryInfo di = new DirectoryInfo(Assembly.GetExecutingAssembly().GetWorkingDirectory());
            foreach (FileInfo file in di.GetFiles("*.*", SearchOption.AllDirectories))
            {
                string ext = file.Extension.Remove(0, 1);

                // usable file?
                if (!serializers.Any(s => string.Equals(ext, s.Extension, StringComparison.InvariantCultureIgnoreCase)))
                {
                    continue;
                }

                IWorldSerializer serializer = serializers.First(s => string.Equals(ext, s.Extension, StringComparison.InvariantCultureIgnoreCase));

                using (FileStream stream = file.Open(FileMode.Open))
                {
                    if (!serializer.IsValid(stream))
                    {
                        continue;
                    }
                }

                _worldFiles.Add(new WorldFile()
                {
                    FileName = file.FullName,
                    Serializer = TypeManager.Instance.GetExportAttribute(serializer.GetType()).Alias,
                });
            }
        }

        #endregion

        #region Nested types

        class WorldFile
        {
            /// <summary>
            /// The file name.
            /// </summary>
            public string FileName;
            /// <summary>
            /// The World serializer to use.
            /// </summary>
            public string Serializer;
        }

        #endregion
    }
}
